<template>
  <div class="hazard">
    <haz-tree-eval @selected="categoryCheckHandler" />
    <div style="flex: 1">
      <el-card shadow="never">
        <div slot="header" style="display: flex;align-items: center;justify-content: space-between;height: 30px;">
          <n-title title="文档智写" />
          <div>
            <el-button type="primary" icon="el-icon-document" size="mini" plain @click="saveContent"
              :loading="saving">保存内容</el-button>
            <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="downloadTemplate('ZHBG.docx')">一键生成报告</el-button>
          </div>


        </div>
        <el-row>
          <el-col :span="24" v-for="(o, index) in 1" :key="o" align="center" :offset="index > 0 ? 1 : 0">
            <el-card :body-style="{ padding: '20px', height: 'calc(100vh - 150px)' }">
                <!-- 确保工具栏容器存在 -->
              <div ref="toolbar"></div>
              <quill-editor v-model="currentContent" :options="editorOptions" ref="editor"
                @change="onEditorChange"></quill-editor>
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue ,Ref} from 'vue-property-decorator';
import HazTreeEval from "@/views/app/components/HazTreeEval.vue";
import NTitle from "@/components/NTitle.vue";
import { quillEditor } from 'vue-quill-editor';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import {
  updateContent
} from '@/api/evaluation';

import { Document, Packer, Paragraph, TextRun } from "docx";
import { saveAs } from "file-saver";

@Component({
  methods: {},
  components: { HazTreeEval, NTitle, quillEditor }
})
export default class evaluation extends Vue {

  @Ref('editor') editor;
  // 编辑器内容
  private currentContent = '';
  private currentLabel: any = '';
  // 当前选中的文档ID
  private currentDocId: string | null = null;
  // 保存状态
  private saving = false;
  // 编辑器配置
  private editorOptions = {
    modules: {
      toolbar: {
        container: [
          [{ "align": [] }],
          [{ "color": [] }],
          [{ "background": [] }],
          [{ "size": ["small", false, "large", "huge"] }], // 预设字号选项
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],
          ['link', 'image'],
          ['clean'],
          [{ 'direction': 'rtl' }],
          ['undo', 'redo'],
          [{'download-word': '⬇'}],
        ],
        handlers: {
          "download-word": this.downloadAsWord
        },
      },

      history: {
        delay: 1000,
        maxStack: 100,
        userOnly: true
      }
    },
    theme: "snow",
    formats: ['size'],
  };

  categoryCheckHandler(data) {

    this.currentLabel = data.label;
    try {
      if (this.editor && this.editor.length > 0) {
        const quill = this.editor[0].quill;
        quill.format('size', 'large'); // 或者使用具体像素值
      }
      this.currentContent =data.extra.content;
      this.currentDocId = data.id;
      this.$message.success('数据加载完成');
    } catch (error) {
      this.$message.error('文档加载失败');
    }
  }

  downloadTemplate(filename) {
      try {
        const link = document.createElement('a')
        link.href = `/files/${filename}` // 注意路径匹配
        link.download = filename
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.$message.success('模板下载成功')
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('模板下载失败')
      }
    }

  downloadAsWord() {
    // 创建 Word 内容
    const doc = new Document({
      sections: [{
        properties: {},
        children: [
          new Paragraph({
            children: [
              new TextRun({
                text: this.currentContent.replace(/<[^>]+>/g, ""), // 去除 HTML 标签
                bold: true,
                size: 24
              })
            ]
          })
        ]
      }]
    });

    // 生成并下载
    Packer.toBlob(doc).then(blob => {
      saveAs(blob, `${this.currentLabel}.docx`);
    });
  }
  // 保存内容
  private async saveContent() {
    console.log(this.currentContent)
    if (!this.currentDocId) {
      this.$message.warning('请先选择文档节点');
      return;
    }

    this.saving = true;
    try {
     updateContent({id:this.currentDocId,content: this.currentContent}).then(res =>{
       this.$message.success('保存成功');
     })
     
    } catch (error) {
      this.$message.error('保存失败');
    } finally {
      this.saving = false;
    }
  }

  // 编辑器内容变化处理
  private onEditorChange({ quill, html, text }) {
    // 可以在此添加自动保存逻辑
    //this.$message.success("文档已修改，点击保存才能生效");
  }

  mounted() {

    this.$nextTick(() => {

      if (this.editor && this.editor.length > 0) {
        const quill = this.editor[0].quill;
        quill.format('size', 'large'); // 或者使用具体像素值
      }

    });

}

}
</script>
<style lang="scss" scoped>
.hazard {
  display: flex;
  gap: 2px;
  height: 100vh;

  .ha-top {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .radio-t {
      display: flex;
      align-items: center;
      gap: 6px;

      span {
        font-size: 14px;
      }
    }
  }
}

.ql-size-12px {
  font-size: 12px !important;
}

.ql-size-14px {
  font-size: 14px !important;
}

.ql-size-16px {
  font-size: 16px !important;
}

.ql-toolbar .download-btn {
  padding: 5px;
  background: #4CAF50;
  color: white;
  border-radius: 3px;
}

/* 自定义下载按钮图标 */
.ql-toolbar button.ql-download-word::before {
  content: "⬇";
  font-style: normal;
}

/* 编辑器样式调整 */
.ql-container {
  height: calc(100vh) !important;
  overflow-y: auto;
}

.ql-toolbar {
  background: #f5f7fa;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

.flex-container {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中，如果需要的话 */
  height: 100px;
  /* 或者任何你想要的高度 */
  color: blue;
  font-weight: 1000;
  //background: url(../../assets/image/deepseek.png) center center no-repeat;

}

.el-tree-select {
  height: 30px !important;

  /* 调整为你需要的高度 */
  input {
    height: 30px !important;
    /* 调整为你需要的高度 */
  }
}

.el-input__inner {
  height: 30px !important;
  /* 调整为你需要的高度 */
}

::v-deep .el-card .el-card__header {
  padding: 6px 10px !important;
}

::v-deep .el-card__body {
  padding: 0px 5px 0px 5px !important;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 480px;
}
</style>
